package br.sc.senai.model.resource;

import jas.date.JASDateTime;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import br.sc.senai.model.exception.EntitiesDAOExcption;

public class ReflectionAux {
	
	public static Object[] getValuesFromEntity(Object pEntity) throws EntitiesDAOExcption{
		return getValuesFromEntity(pEntity, false);
	}
	
	public static Object[] getValuesFromEntity(Object pEntity, Boolean pIsWithId) throws EntitiesDAOExcption{
		
		try {
			Field[] mListFieds =  pEntity.getClass().getDeclaredFields();
			
			List<Object> mListValues = new ArrayList<Object>();
			
			for (Field field : mListFieds) {
				field.setAccessible(true);
				
				Object mValueField = field.get(pEntity);
				
				if (String.class.getSimpleName().equals(mValueField.getClass().getSimpleName())){
					mValueField = String.format("'%s'", mValueField);
				} else if (Date.class.getSimpleName().equals(mValueField.getClass().getSimpleName())){
					mValueField = String.format("'%s'", JASDateTime.toFormatSqlDate((Date) mValueField));
				} else if (java.sql.Timestamp.class.getSimpleName().equals(mValueField.getClass().getSimpleName())){
					Timestamp mTimestamp = (Timestamp) mValueField;
					mValueField = String.format("'%s'", JASDateTime.toFormat((new java.util.Date(mTimestamp.getTime())) , "yyyy-MM-dd HH:mm:ss"));
				}
				mListValues.add(mValueField);
			}
			
			if (pIsWithId)
				mListValues.add(pEntity.getClass().getMethod("getId").invoke(pEntity));
			return mListValues.toArray();
		} catch (Exception e) {
			throw new EntitiesDAOExcption(String.format(Mensagens.ERRO_INESPERADO, "Pegar valores do objeto."), e);
		}
	}
}
